<template>
  <el-dialog
    :title="showNew ? (dataForm.id ? '修改商品规格': '新建商品规格' ) : '商品规格'"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    :visible.sync="visible"
    :fullscreen="true">
    <div v-show="imgVisible">
      <img :src="imgName" style="width:50%;"/>
    </div>
    <div v-show="!imgVisible">
      <div v-show="!showNew">
        <el-table
          :data="dataList"
          border
          stripe
          v-loading="dataListLoading"
          @selection-change="selectionChangeHandle"
          :height=tableHeight
          style="width: 100%;">
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            fixed="left"
            header-align="center"
            align="left"
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            prop="goodsName"
            header-align="center"
            align="center"
            label="商品">
          </el-table-column>
          <el-table-column
            prop="specificationName"
            header-align="center"
            align="center"
            label="规格"
            width="200">
          </el-table-column>
          <el-table-column
            prop="value"
            header-align="center"
            align="center"
            label="规格说明">
          </el-table-column>
          <el-table-column
            prop="picUrl"
            header-align="center"
            align="center"
            label="规格图片"
            width="200">
            <template slot-scope="scope">
              <img :src="scope.row.picUrl" class="picture" v-show="scope.row.picUrl" @click="handleView(scope.row.picUrl)"/>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-button v-if="isAuth('goodsSpecification:update')" type="text" size="small" @click="showNewView(scope.row.id)">修改</el-button>
              <el-button v-if="isAuth('goodsSpecification:delete')" type="text" size="small" @click="deleteHandle(scope.row.id)" class="delete-button">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="showNew">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
          <el-form-item label="规格" prop="specificationId">
            <el-select
              clearable
              v-model="dataForm.specificationId"
              placeholder="请选择规格"
              style="width: 100%;">
              <el-option
                v-for="item in specificationList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="规格说明" prop="value">
            <el-input v-model="dataForm.value" placeholder="请输入规格说明" maxlength="50" clearable></el-input>
          </el-form-item>
          <el-form-item label="规格图片" prop="picUrl">
            <el-upload
              class="avatar-uploader"
              :action="updateUrl"
              :show-file-list="false"
              :on-success="handlePicUrlSuccess"
              :before-upload="beforePicUpload">
              <div v-if="dataForm.picUrl" @click.stop="handleView()">
                <img :src="dataForm.picUrl" class="pic-url"/>
                <div class="upload-list-cover">
                  <i class="el-icon-delete" @click.stop="deleteBtn(dataForm.picUrl)"></i>
                  <i class="el-icon-view" @click.stop="handleView(dataForm.picUrl)"></i>
                </div>
              </div>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!--图片查看页控制按钮-->
    <span slot="footer" class="dialog-footer" v-show="imgVisible">
        <el-button type="primary" @click="hideView()">退出图片查看</el-button>
    </span>
    <!--新建页控制按钮-->
    <span slot="footer" class="dialog-footer" v-show="!imgVisible && showNew">
        <el-button type="primary" @click="dataFormSubmit()">提交</el-button>
        <el-button @click="hideNewView()">取消</el-button>
    </span>
    <!--主页控制按钮-->
    <span slot="footer" class="dialog-footer" v-show="!imgVisible && !showNew">
      <el-button type="primary" @click="showNewView()">新建</el-button>
      <el-button v-if="isAuth('goodsSpecification:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
      <el-button @click="cancel()">返回</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        // 对话框是否显示
        visible: false,
        dataList: [],
        dataListLoading: false,
        // 图片预览参数
        imgName: '',
        imgVisible: false,
        showNew: false,
        dataForm: {
          id: 0,
          goodsId: '',
          specificationId: '',
          value: '',
          picUrl: ''
        },
        dataRule: {
          specificationId: [
            { required: true, message: '规格不能为空', trigger: 'blur' }
          ],
          value: [
            { required: true, message: '规格说明不能为空', trigger: 'blur' }
          ]
        },
        specificationList: [],
        // 图片上传路径
        updateUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        // 旧图片
        oldImg: [],
        // 新图片
        newImg: [],
        // 多选项集合
        dataListSelections: []
      }
    },
    computed: {
      tableHeight: function () {
        return this.$store.state.common.documentClientHeight - 180
      }
    },
    methods: {
      // 初始化
      init (goodsId) {
        this.dataForm.goodsId = goodsId
        this.getDataList()
        this.visible = true
      },
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/back/goodsSpecification/list'),
          method: 'get',
          params: this.$http.adornParams({
            'goodsId': this.dataForm.goodsId
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.data.list
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      // 显示新建/修改表单
      showNewView (id) {
        if (id) {
          this.getGoodsSpecificationInfo(id)
        }
        this.getSpecifications()
        this.showNew = true
      },
      // 隐藏新建/修改表单
      hideNewView () {
        this.deletePics(this.newImg)
        this.showNew = false
        this.newImg = []
        this.oldImg = []
        this.dataForm.id = 0
        this.dataForm.specificationId = ''
        this.dataForm.value = ''
        this.dataForm.picUrl = ''
      },
      // 查看图片
      handleView (imgUrl) {
        if (!imgUrl) { return }
        this.imgName = imgUrl
        this.imgVisible = true
      },
      // 关闭图片查看
      hideView () {
        this.imgVisible = false
      },
      // 获取规格列表
      getSpecifications () {
        this.$http({
          url: this.$http.adornUrl('/back/specification/list'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.specificationList = data.data.list
          } else {
            this.specificationList = []
          }
        })
      },
      // 获取规格信息
      getGoodsSpecificationInfo (id) {
        this.$http({
          url: this.$http.adornUrl(`/back/goodsSpecification/info/${id}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataForm.id = id
            this.dataForm.specificationId = data.data.specificationId
            this.dataForm.value = data.data.value
            this.dataForm.picUrl = data.data.picUrl
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/back/goodsSpecification/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                id: this.dataForm.id || undefined,
                goodsId: this.dataForm.goodsId,
                specificationId: this.dataForm.specificationId,
                value: this.dataForm.value,
                picUrl: this.dataForm.picUrl
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.deletePics(this.oldImg)
                this.showNew = false
                this.getDataList()
                this.newImg = []
                this.oldImg = []
                this.dataForm.id = 0
                this.dataForm.specificationId = ''
                this.dataForm.value = ''
                this.dataForm.picUrl = ''
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 上传图片之前的钩子
      beforePicUpload (file) {
        var fileType = ['image/jpeg', 'image/png', 'image/jpg']
        const isPic = fileType.join(',').indexOf(file.type) !== -1
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isPic) {
          this.$message.error('不支持此格式的图片!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return isPic && isLt2M
      },
      // 图片上传成功时的钩子
      handlePicUrlSuccess (response) {
        if (response && response.code === 0) {
          this.dataForm.picUrl = response.url
          this.newImg.push(response.url)
        } else {
          this.$message.error(response.msg)
        }
      },
      // 图片删除按钮点击事件
      deleteBtn (url) {
        if (url) {
          this.oldImg.push(url)
          this.dataForm.picUrl = ''
        }
      },
      // 删除图片数组
      deletePics (deleteImg) {
        for (var i = 0; i < deleteImg.length; i++) {
          this.deletePic(deleteImg[i])
        }
      },
      // 通过url删除图片
      deletePic (url) {
        this.$http({
          url: this.$http.adornUrl('/sys/oss/deleteByUrl'),
          method: 'post',
          params: this.$http.adornParams({'url': url})
        })
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/back/goodsSpecification/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {})
      },
      // 取消操作
      cancel () {
        var that = this
        that.$emit('closeDialog')
        that.visible = false
      }
    }
  }
</script>

<style>
  .picture{
    width:3rem;
    height:3rem;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
  .pic-url {
    width: 100%;
    height: 100%;
    display: block;
  }
  .upload-list-cover{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, .6);
    color:#ffffff;
    display:flex;
    display: -webkit-flex;
    justify-content: space-around;
    align-items: center;
    font-size: 20px;
  }
</style>
